package com.iot.task;

import com.alibaba.fastjson2.JSONObject;
import com.iot.entity.DeviceConfig;
import com.iot.mqtt.MqttHelper;
import com.iot.service.DeviceConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 定时下发待发送的配置（device_config.status = pending）
 * 每小时检查一次待下发的配置，并发送到对应设备
 */
@Component
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ConfigDispatchTask {

    private final DeviceConfigService configService;

    @Scheduled(cron = "0 0 * * * ?") // 每小时执行一次
    public void dispatchPendingConfig() {
        log.info("开始下发 pending 配置任务...");
        List<DeviceConfig> pendingList = configService.getPendingConfigs();

        for (DeviceConfig config : pendingList) {
            JSONObject payload = new JSONObject();
            payload.put("configKey", config.getConfigKey());
            payload.put("configValue", config.getConfigValue());

            String topic = "device/" + config.getDeviceId() + "/config";
            try {
                MqttHelper.getInstance().send(topic, payload.toJSONString().getBytes(StandardCharsets.UTF_8));
                config.setStatus("sent");
                configService.updateConfig(config);
                log.info("已下发配置：{}", payload);
            } catch (Exception e) {
                log.warn("配置下发失败: {}", e.getMessage());
            }
        }
    }
}
